# encoding:UTF-8
# _*_ coding:utf-8 _*_
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask import url_for
import json
from model import *

import sys

reload(sys)
sys.setdefaultencoding('utf8')

import ValidCheck

app = Flask(__name__)


@app.route('/')
def index():
    args = request.args
    args = args.to_dict()
    if args.has_key('page'):
        page = args['page']
    else:
        page = 0

    page = int(page)
    books = Book.get_book_range(page * 40, 40)

    statusmap = {1: "图片就绪", 2: "图片声音就绪", 3: "文字就绪", 4: "上线"}

    return render_template("index.xhtml",
                           num=Book.get_count() / 40 + 1,
                           books=books,
                           statusmap=statusmap)

@app.route('/book')
def bookdetail():
    args = request.args
    args = args.to_dict()
    bookid = args['id']

    pages = Pic.get_pages(bookid)
    book = Book.find_by_id(bookid)
    series = Series.get_all()

    return render_template("book.xhtml",
                           pages=pages,
                           book=book,
                           series=series)


@app.route('/update', methods=['GET', 'POST'])
def update_book():
    args = request.args
    args = args.to_dict()
    book = Book.find_by_id(args['id'])

    if not args.has_key('seriesid'):
        args['seriesid'] = 0

    book.update(args['name'], args['desc'], args['seriesid'], args['status'])
    return redirect(url_for('bookdetail', id=args['id']))

# 客户端请求
@app.route('/picbook', methods=['GET', 'POST'])
def picbook():
    args = request.args
    args = args.to_dict()
    if not ValidCheck.check(args):
        return 'err sign'
    data = args['data']
    if not data:
        return 'no data'
    data = eval(data)
    print 'picbook', data

    if cmp(args['api'], 'booklist') == 0:
        start = int(data['start'])
        pagesize = int(data['pageSize'])
        ret = Book.get_book_range(start, pagesize)
        ret = {"books": ret}
        return formatjson(ret)

    if cmp(args['api'], 'pages') == 0:
        bookid = int(data['bookid'])
        ret = Pic.get_pages(bookid)
        ret ={"pages":ret}
        return formatjson(ret)


def formatjson(data):
    ret = {"code": 0, "data": data, "msg": ""}
    return json.dumps(ret, separators=(',', ':'))


if __name__ == '__main__':
    app.debug = True
    app.run('0.0.0.0', port=8080)
else:
    application = app.wsgi_app
